#include "Actions/ActionSelectObject.h"

using namespace Ogre;
ActionSelectObject::ActionSelectObject(Ogre::Camera *mCam, Ogre::SceneManager *ScrMgr, Ogre::RaySceneQuery* ray){
	mCamera=mCam;
	mRaySceneQuery=ray;
	mSceneMgr=ScrMgr;
}

ActionSelectObject::~ActionSelectObject(){}

bool ActionSelectObject::mousePressed(const OIS::MouseEvent &evt){

	SceneNode* mCurrentObjectFound;
	deselected=false;

    Ray mouseRay = mCamera->getCameraToViewportRay(0.5f, 0.5f);

	mRaySceneQuery->setRay(mouseRay);
	mRaySceneQuery->setSortByDistance(true);
	RaySceneQueryResult &result = mRaySceneQuery->execute();
	RaySceneQueryResult::iterator itr = result.begin( );	
	Real closestDistance = 100000;
	bool found=false;

	for (itr = result.begin(); itr != result.end() ; itr++)
	{
		if(itr->movable && closestDistance>(*itr).distance && (*itr).movable->getMovableType() != "TerrainMipMap" ){

			mCurrentObjectFound=itr->movable->getParentSceneNode();
			found=true;
		}
	}

	if(mCurrentObjectFound == mCurrentObject)
		deselected=true;

	mCurrentObject=mCurrentObjectFound;

	//if(!moveObject)
	//	delete moveObject;
	//moveObject = new ActionMoveObject(mCamera,mCurrentObject,mRaySceneQuery);

	return found;
}

SceneNode* ActionSelectObject::getSelectedNode(){

	return mCurrentObject;
}

ActionMoveObject* ActionSelectObject::getActionMoveObject(){

	return new ActionMoveObject(mCamera,mCurrentObject,mRaySceneQuery);
}

bool ActionSelectObject::isDeselected(){

	return deselected;
}